﻿using System;
using System.Collections;
using System.Collections.Generic;
using Me.Prettyprint.Cassandra.Connection;
using Me.Prettyprint.Cassandra.Serializers;
using Me.Prettyprint.Cassandra.Service;
using Me.Prettyprint.Cassandra.Utils;
using Me.Prettyprint.Hector.Api;
using Me.Prettyprint.Hector.Api.Beans;
using Me.Prettyprint.Hector.Api.Query;
using Org.Apache.Cassandra.Thrift;

namespace Me.Prettyprint.Cassandra.Model
{
    /// <summary>
    /// ColumnSliceImpl is the default implementation of ColumnSlice interface. The implementation takes
    /// a list of thrift columns and converts them to HColumn.
    /// </summary>
    /// <typeparam name="N"></typeparam>
    /// <typeparam name="V"></typeparam>
    public class ColumnSliceImpl<N, V> : ColumnSlice<N, V>
    {
        public ColumnSliceImpl(List<Column> tColumns, Serializer<N> nameSerializer,
            Serializer<V> valueSerializer)
        {
            if (tColumns == null || nameSerializer == null || valueSerializer == null)
            {
                throw new NullReferenceException("Thrift column, Name serializer and Value serializer cannot be null");
            }
            List<HColumn<N, V>> list = new List<HColumn<N, V>>(tColumns.Count);
            foreach (Column c in tColumns)
            {
                HColumn<N, V> column = new HColumnImpl<N, V>(c, nameSerializer, valueSerializer);
                list.Add(column);
            }
            ColumnsList = list;
        }
        public Dictionary<N, HColumn<N, V>> ColumnsDictionary
        {
            get;
            set;
        }
        public List<HColumn<N,V>> ColumnsList
        {
            get;
            set;
        }
        public List<HColumn<N,V>> GetColumns()
        {
            return ColumnsList;
        }
        public HColumn<N, V> GetColumnByName(N columnName)
        {
            if ( null == ColumnsDictionary)
            {
                ColumnsDictionary = new Dictionary<N,HColumn<N,V>>(ColumnsList.Count);
                foreach (HColumn<N, V> column in ColumnsList)
                {
                    ColumnsDictionary[column.Name] = column;
                }
            }
            return ColumnsDictionary[columnName];
        }
        public override string ToString()
        {
            return string.Format("ColumnSlice({0})", ColumnsList.ToString());
        }
    }
}
